package com.tongtailian.www.stir.activity;

import android.androidlib.ui.view.alertview.AlertView;
import android.androidlib.ui.view.alertview.OnItemClickListener;
import android.androidlib.utils.ACache;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Parcel;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.data.BleDevice;
import com.tongtailian.www.stir.MyApplication;
import com.tongtailian.www.stir.R;
import com.tongtailian.www.stir.adapter.HomeSampleAdapter;
import com.tongtailian.www.stir.base.BaseActivity;
import com.tongtailian.www.stir.bean.BaseDataFramType;
import com.tongtailian.www.stir.bean.ConfigBean;
import com.tongtailian.www.stir.bean.ConfigDataFram;
import com.tongtailian.www.stir.bean.DeviceModleFram;
import com.tongtailian.www.stir.bean.DeviceStateFram;
import com.tongtailian.www.stir.bean.NumberBean;
import com.tongtailian.www.stir.bleinterface.MyBleDeviceModleCallBack;
import com.tongtailian.www.stir.bleinterface.MyBleDeviceStateCallBack;
import com.tongtailian.www.stir.bleinterface.MyBleGattCallback;
import com.tongtailian.www.stir.comm.Observer;
import com.tongtailian.www.stir.comm.ObserverManager;
import com.tongtailian.www.stir.fragment.MyDialogFragment;
import com.tongtailian.www.stir.utils.BleManageUtil;
import com.tongtailian.www.stir.utils.LogUtil;
import com.tongtailian.www.stir.utils.ParcelableUtil;
import com.tongtailian.www.stir.utils.SoundPlayer;
import com.tongtailian.www.stir.utils.ToastUtils;
import com.tongtailian.www.stir.utils.gson.GsonUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import me.jessyan.autosize.AutoSizeCompat;

public class MainActivity580 extends BaseActivity implements View.OnClickListener, Observer {



    MyBleDeviceStateCallBack myBleDeviceStateCallBack = null;
    MyBleDeviceModleCallBack myBleDeviceModleCallBack = null;

    private long firstTime = 0;
    private boolean errorDialogShow = false;


    private List<NumberBean> demoLocationList = new ArrayList<>();//样品数量
    private List<NumberBean> runningDemoLocationList = new ArrayList<>();//运行中的样品数量
    private List<ConfigBean> circleStateList = new ArrayList<>();

    private List<RelativeLayout[]> group_views_list = new ArrayList<>();
    private List<ImageView[]> group_state_views_list = new ArrayList<>();

    private RelativeLayout[] group_1;
    private ImageView[] group_1_state;

    private RelativeLayout[] group_2;
    private ImageView[] group_2_state;

    private RelativeLayout[] group_3;
    private ImageView[] group_3_state;

    private RelativeLayout[] group_4;
    private ImageView[] group_4_state;

    private BleManageUtil bleManageUtil;
    private MyDialogFragment myDialogFragment;

    private CountDownTimer timer;//定时器查询工作状态
    private String locationList;
    private int dataDev;
    private int flow;
    private int modle;

    private int doingIndex = -1;
    private int oldDoingIndex = -1;
    private Chronometer chronometer;
    private SoundPlayer soundPlayer;

    ACache aCache;
    private BleDevice cacheBleDevice;
    private RelativeLayout rlGroup11,rlGroup12,rlGroup21,rlGroup22,rlGroup31,rlGroup32,rlGroup41,rlGroup42;
    private ImageView ivGroup11,ivRoup12,ivGroup21,ivRoup22,ivGroup31,ivRoup32,ivGroup41,ivRoup42;
    private TextView tvGroupState;
    private ImageView ivPlayState;
    private TextView tvMode;
    private LinearLayout llPlay;
    private TextView btHelp;
    private TextView btSlectParame;
    private LinearLayout llBluetoochSetting;
    private TextView tv_group_custom,tv_group_default,tv_changee_knife,tv_loop_num,tv_wish_pipe,tv_wish_knife;
    private int loopNum = 1;
    private int curLoopNum = 1;
    private boolean isLoop;
    private boolean isWhisKnife;
    private boolean isWhisPipe;
    private boolean isChangeKnife;
    private int name;

    String nameArray[] = {"根茎类", "叶菜类", "花果菜类", "干果类", "水果类", "谷物类", "鱼肉类", "其他类", "维护更换转刀"};
    String valueArray[] = {"样品重量≤500克，如：萝卜、胡萝卜、豆薯、甘薯、主要有莴笋、茎用芥菜、球茎甘蓝、竹笋、土豆、莲藕、洋葱、大蒜等。",
            "样品重量≤500克，如：白菜、菠菜、苋菜、莴苣、韭菜、芹菜等",
            "样品重量≤500克，如：金针菜、花椰菜、紫菜薹、南瓜、黄瓜、冬瓜、丝瓜、番茄、辣椒、茄子、豆角等",
            "样品重量≤500克，如：杏仁、腰果、榛子、核桃、板栗、白果、花生、葵花子、南瓜子、板栗、杏仁等（坚果类需去壳）",
            "样品重量≤500克，如：草莓、蓝莓、覆盆子、橘子、柠檬、柚子、葡萄、桃、枣、龙眼、荔枝、苹果、梨、柿子等",
            "样品重量≤500克，如：薏米、高梁、大麦、糙米、红小豆、小米、黑豆、黄豆等",
            "样品重量≤500克，如：活鱼、虾、海鲜、牛肉、羊肉、猪肉。含内脏含熟食",
            "样品重量≤500克，难处理的样品：粉丝、西兰花、蒜苗等",
            "维护更换转刀"};
    private List<ConfigBean> runTypelist = new ArrayList<>();//研磨模式
    private boolean isDouble = true;
    private AlertView mHistoryAlertView;

    @Override
    public int setLayoutId() {
        return R.layout.activity_580_main;
    }

    @Override
    public void initVariables() {
        setTitle("TTL-580型全自动刀式研磨仪");
        bleManageUtil = BleManageUtil.getInstance();//初始化蓝牙
        //选中几号 座机位
        locationList = spManager.getLocationList();
        soundPlayer = new SoundPlayer(this);
    }


    @Override
    public void initViews(Bundle savedInstanceState) {
        rlGroup11 = findViewById(R.id.rl_group_1_1);
        rlGroup12 = findViewById(R.id.rl_group_1_2);
        rlGroup21 = findViewById(R.id.rl_group_2_1);
        rlGroup22 = findViewById(R.id.rl_group_2_2);
        rlGroup31 = findViewById(R.id.rl_group_3_1);
        rlGroup32 = findViewById(R.id.rl_group_3_2);
        rlGroup41 = findViewById(R.id.rl_group_4_1);
        rlGroup42 = findViewById(R.id.rl_group_4_2);

        ivGroup11 = findViewById(R.id.iv_group_1_1);
        ivRoup12 = findViewById(R.id.iv_roup_1_2);
        ivGroup21 = findViewById(R.id.iv_group_2_1);
        ivRoup22 = findViewById(R.id.iv_roup_2_2);
        ivGroup31 = findViewById(R.id.iv_group_3_1);
        ivRoup32 = findViewById(R.id.iv_roup_3_2);
        ivGroup41 = findViewById(R.id.iv_group_4_1);
        ivRoup42 = findViewById(R.id.iv_roup_4_2);

        tvGroupState = findViewById(R.id.tv_group_state);
        ivPlayState = findViewById(R.id.iv_play_state);
        chronometer = findViewById(R.id.chronometer);

        tvMode = findViewById(R.id.tv_mode);

        llPlay = findViewById(R.id.ll_play);
        btHelp = findViewById(R.id.bt_help);
        btSlectParame = findViewById(R.id.bt_slect_parame);
        llBluetoochSetting = findViewById(R.id.ll_bluetooch_setting);

        tv_group_custom = findViewById(R.id.tv_group_custom);
        tv_group_default = findViewById(R.id.tv_group_default);
        tv_changee_knife = findViewById(R.id.tv_changee_knife);
        tv_loop_num = findViewById(R.id.tv_loop_num);
        tv_wish_pipe = findViewById(R.id.tv_wish_pipe);
        tv_wish_knife = findViewById(R.id.tv_wish_knife);


        btHelp.setOnClickListener(this);
        btSlectParame.setOnClickListener(this);
        llBluetoochSetting.setOnClickListener(this);
        llPlay.setOnClickListener(this);

        tv_group_custom.setOnClickListener(this);
        tv_group_default.setOnClickListener(this);
        tv_changee_knife.setOnClickListener(this);
        tv_loop_num.setOnClickListener(this);
        tv_wish_pipe.setOnClickListener(this);
        tv_wish_knife.setOnClickListener(this);

    }


    @Override
    public void doBusiness() {
        initPermissions();
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "当前设备不支持BLE蓝牙4.0", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        updateList();
        updategroupList();

        initData();
        ObserverManager.getInstance().addObserver(this);

        bleManageUtil.initData(this);
        updateCircleLocation();

    }


    private void updateList(){
        String runType = spManager.getRunType();
        LogUtil.d("获取的runType = " + locationList);
        LogUtil.d("nameArray.length = "+nameArray.length);
        if (TextUtils.isEmpty(runType)) {
            for (int i = 1; i <= 63; i++) {
                ConfigBean bean = new ConfigBean();

                if (i <= nameArray.length) {
                    bean.setLook("查看");
                    bean.setEdit(false);
                    bean.setName(nameArray[i - 1]);
                    bean.setValue(valueArray[i - 1]);
                } else {
                    bean.setLook("编辑");
                    bean.setEdit(true);
                    bean.setName("自定义" + String.valueOf(i - 1));
                }
                bean.setSelect(false);
                runTypelist.add(bean);
            }
            LogUtil.d("保存的 = " + GsonUtil.gsonString(runTypelist));
            spManager.saveRunType(GsonUtil.gsonString(runTypelist));
        } else {
            runTypelist = GsonUtil.jsonToList(runType, ConfigBean.class);
            LogUtil.d("获取的的 = " + GsonUtil.gsonString(runTypelist));
        }
    }

    public void updategroupList(){
        locationList = spManager.getLocationList();
        LogUtil.d("locationList = " + locationList);
        if (TextUtils.isEmpty(locationList)) {
            for (int i = 1; i <= 4; i++) {
                NumberBean bean = new NumberBean();
                bean.setName(String.valueOf(i) + "号");
                bean.setGroup_name("根茎类");
                bean.setGroup(0);
                bean.setSelect(true);
                demoLocationList.add(bean);
            }
            spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
        } else {
            demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(spManager.getCurModle() == 1){
            updateModeText();
            if(bleManageUtil.isPlaying){
                if(!compareList()){
                    ToastUtils.showCenter("取消设备");
                    bleManageUtil.createConfirmOrCancleData(1,demoLocationList);
                }
            }
        }
        else{
            if(doingIndex > 0)
                updateCustomModeText(doingIndex);
            else
                updateCustomModeText(0);
        }
        //getFirstDeviceModle();
        // = false;
        updateCircleLocation();
    }

    public boolean compareList(){
        if(runningDemoLocationList.size() == 0)
            return true;
        for (int i = 0; i < demoLocationList.size(); i++) {
            Boolean b1 = demoLocationList.get(i).isSelect();
            Boolean b2 = runningDemoLocationList.get(i).isSelect();
            if(!b1.equals(b2))
                return false;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_group_custom:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                startActivity(SelectCustomParameActivity.class);

                break;
            case R.id.tv_group_default:

                intent = new Intent();
                intent.setClass(mContext,SelectParameActivity.class);
                intent.putExtra("isDef",true);
                startActivity(intent);
                break;
            case R.id.tv_changee_knife:
                //getDevicemodle();
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                showChangeKnifeDialog("请先拆除所有样品罐");
                break;
            case R.id.tv_loop_num:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                startActivity(SelectLoopNumActivity.class);
                break;
            case R.id.tv_wish_pipe:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                showWhisPipeDialog("清洗管路");
                break;
            case R.id.tv_wish_knife:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                showWhisDialog("清洗转刀");
                break;

            case R.id.ll_play:
                //开启流程
                if (!demoLocationList.get(0).isSelect()) {
                    ToastUtils.showCenter("请选择样品座");
                    return;
                }
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }

                if (BleManageUtil.getInstance().isPlaying) {
                    showCloseDialog();
                } else {
                    //先检查工作模式
                    getDeviceModle();
                    /*if(spManager.getCurModle() == 1)
                        start();
                    else
                        startCustom();*/
                    //isDouble = false;
                    //showRunModleConnectDialog(" 第二排刀头已停止工作\n请确保第二排样品罐为空");

                }

                break;
            case R.id.bt_slect_parame:
                if (!BleManageUtil.getInstance().isConnect) {
                    ToastUtils.showCenter("暂未连接蓝牙设备");
                    stop();
                    return;
                }
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止设备");
                    return;
                }
                intent = new Intent();
                intent.setClass(mContext,SelectParameActivity.class);
                intent.putExtra("isDef",false);
                startActivity(intent);
                break;
            case R.id.ll_bluetooch_setting:
                if (BleManageUtil.getInstance().isPlaying) {
                    ToastUtils.showCenter("设备运转中请先停止");
                    return;
                }
                showBlueToochFragment();
                break;
            case R.id.bt_help:
                startActivity(HelpActivity.class);
                break;
        }
    }

    private void getDeviceModle() {

        if(myBleDeviceModleCallBack == null) {
            myBleDeviceModleCallBack = new MyBleDeviceModleCallBack() {
                @Override
                public void onDevicesState(DeviceModleFram deviceModleFram) {
                    modle = deviceModleFram.getModle();
                    LogUtil.d("deviceModleFram'getModle = " + modle);
                    LogUtil.d(" deviceModleFram 当前设备模式 = " + GsonUtil.gsonString(deviceModleFram));

                    switch (modle) {
                        case 1:
                            isDouble = false;
                            LogUtil.d(" deviceModleFram 当前设备模式 = 单路模式");
                            showRunModleConnectDialog(" 第二排刀头已停止工作\n请确保第二排样品罐为空");
                            break;
                        case 2:
                            isDouble = true;
                            LogUtil.d(" deviceModleFram 当前设备模式 = 双路模式");
                            if (spManager.getCurModle() == 1)
                                start();
                            else
                                startCustom();
                            break;
                    }

                }

                @Override
                public void onFail() {
                    ToastUtils.showCenter("设备状态读取失败");
                }
            };
        }

        BleManageUtil.getInstance().readDevicesModle(myBleDeviceModleCallBack);


    }
    private void getFirstDeviceModle() {

        if(myBleDeviceModleCallBack == null) {
            myBleDeviceModleCallBack = new MyBleDeviceModleCallBack() {
                @Override
                public void onDevicesState(DeviceModleFram deviceModleFram) {
                    modle = deviceModleFram.getModle();
                    LogUtil.d("deviceModleFram'getModle = " + modle);
                    LogUtil.d(" deviceModleFram 当前设备模式 = " + GsonUtil.gsonString(deviceModleFram));

                    switch (modle) {
                        case 1:
                            isDouble = false;
                            LogUtil.d(" deviceModleFram 当前设备模式 = 单路模式");
                            break;
                        case 2:
                            isDouble = true;
                            LogUtil.d(" deviceModleFram 当前设备模式 = 双路模式");
                    }
                    updateCircleLocation();
                }

                @Override
                public void onFail() {

                }
            };

        }
        BleManageUtil.getInstance().readDevicesModle(myBleDeviceModleCallBack);


    }

    private void initData() {

        group_1 = new RelativeLayout[]{rlGroup11, rlGroup12};
        group_1_state = new ImageView[]{ivGroup11, ivRoup12};

        group_2 = new RelativeLayout[]{rlGroup21, rlGroup22};
        group_2_state = new ImageView[]{ivGroup21, ivRoup22};

        group_3 = new RelativeLayout[]{rlGroup31, rlGroup32};
        group_3_state = new ImageView[]{ivGroup31, ivRoup32};

        group_4 = new RelativeLayout[]{rlGroup41, rlGroup42};
        group_4_state = new ImageView[]{ivGroup41, ivRoup42};

        group_views_list.add(group_1);
        group_views_list.add(group_2);
        group_views_list.add(group_3);
        group_views_list.add(group_4);

        group_state_views_list.add(group_1_state);
        group_state_views_list.add(group_2_state);
        group_state_views_list.add(group_3_state);
        group_state_views_list.add(group_4_state);

        try {
            getLocationBlue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (cacheBleDevice != null) {
            if (myDialogFragment == null) {
                showBlueToochFragment();
            }
            showHistoryConnectDialog("检测到历史连接记录,是否重新连接?", cacheBleDevice);
        }
    }

    //设置圆圈背景
    private void updateCircleLocation() {
        LogUtil.d("locationList = " + locationList);
        //选中第几组 座机位
        locationList = spManager.getLocationList();
        if (!TextUtils.isEmpty(locationList)) {
            demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
            NumberBean numberBean;
            boolean isSel;
            for (int i = 0; i < demoLocationList.size(); i++) {
                numberBean = demoLocationList.get(i);
                isSel = numberBean.isSelect();
                LogUtil.d("第" + (i + 1) + "一个 是否选中 = " + isSel);
                if (isSel) {
                    if (doingIndex == (i + 1)) {

                        group_state_views_list.get(i)[0].setVisibility(View.VISIBLE);
                        group_state_views_list.get(i)[0].setBackgroundResource(R.mipmap.refresh);
                        if(isDouble){//第二排研墨中图标 显示 (双排模式)
                            group_state_views_list.get(i)[1].setVisibility(View.VISIBLE);
                            group_state_views_list.get(i)[1].setBackgroundResource(R.mipmap.refresh);
                        }
                        else//第二排不显示(单排模式)
                            group_state_views_list.get(i)[1].setVisibility(View.GONE);

                    } else {
                        group_state_views_list.get(i)[0].setVisibility(View.GONE);
                        group_state_views_list.get(i)[1].setVisibility(View.GONE);
                    }
                    group_views_list.get(i)[0].setBackgroundResource(R.mipmap.home_circle_action);
                    if(isDouble)//第二排选中图片 显示 (双排模式)
                        group_views_list.get(i)[1].setBackgroundResource(R.mipmap.home_circle_action);
                    else//第二排不显示(单排模式)
                        group_views_list.get(i)[1].setBackgroundResource(R.mipmap.home_circle);
                } else {
                    group_views_list.get(i)[0].setBackgroundResource(R.mipmap.home_circle);
                    group_views_list.get(i)[1].setBackgroundResource(R.mipmap.home_circle);
                    group_state_views_list.get(i)[0].setVisibility(View.GONE);
                    group_state_views_list.get(i)[1].setVisibility(View.GONE);
                }
            }

        }

    }

    private void showConnectDialog(String msg, final BleDevice bleDevice) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"连接"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
//                    submit(0);
                    ToastUtils.showCenter("正在重新连接");
                    BleManageUtil.getInstance().connect(bleDevice);
                } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showHistoryConnectDialog(String msg, final BleDevice bleDevice) {
        if(mHistoryAlertView == null){
            mHistoryAlertView = new AlertView("", msg, "取消", new String[]{"连接"},
                    null, this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    if (position == 0) {
//                    submit(0);
                        ToastUtils.showCenter("正在重新连接");
                        BleManageUtil.getInstance().connect(bleDevice);
                    } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                    }
                }
            }).setCancelable(false);
        }
        mHistoryAlertView.show();
    }



    private void showBlueToochFragment() {
        if (myDialogFragment == null) {
            myDialogFragment = MyDialogFragment.newInstance(0);
            myDialogFragment.setInterface(new MyDialogFragment.Mydialoginterface() {
                @Override
                public void cancel() {
                    LogUtil.d("cancel");
                }

                @Override
                public void dismiss() {
                    LogUtil.d("dismiss");

                }
            });
        }
        myDialogFragment.show(getSupportFragmentManager(), "bluetoch");
    }

    /**
     * 获取设备状态
     */
    private void getDeviceState() {
        /**
         * Flow
         * 0x01 位置初始化
         * 0x02 定位流程
         * 0x03 超声波清洗
         * 0x04 热风烘干
         * 0x05 清水清洗
         * 0x06 研磨工作
         *
         * 正常流程结束，Flow = 0x06， Step = 0xA0.
         * 指令结束流程，Flow = 0x10， Step = 0xA0.
         * 异常结束流程，Flow = 0x10， Step = 0xA0.
         */
        if (myBleDeviceStateCallBack == null) {
            myBleDeviceStateCallBack = new MyBleDeviceStateCallBack() {

                @Override
                public void onDevicesState(DeviceStateFram deviceStateFram) {

                    //{name=1, Flow=6, Step=0, DataDev=0}
                    flow = deviceStateFram.getFlow();
                    int step = deviceStateFram.getStep();
                    LogUtil.d("errorDialogShow = " + errorDialogShow);

                    dataDev = deviceStateFram.getDataDev();
                    name = deviceStateFram.getName();
                    LogUtil.d(" 当前设备状态 = " + GsonUtil.gsonString(deviceStateFram));


                    switch (flow) {
                        case 0:
                            tvGroupState.setText("设备已停止");
                            doingIndex = -1;
                            updateCircleLocation();
                            ivPlayState.setBackgroundResource(R.mipmap.play);
                            bleManageUtil.isPlaying = false;
                            break;
                        case 1:
                            tvGroupState.setText("位置初始化中");
                            doingIndex = -1;
                            updateCircleLocation();
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            break;
                        case 3:
                            //超声波清洗
                            tvGroupState.setText("超声波清洗中");
                            doingIndex = -1;
                            updateCircleLocation();
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            //E1 是出错
                            if (225 == step) {
                                if (!errorDialogShow) {
                                    showErrorDialogOne("超声波清洗错误,请检查供水");
                                }
                            }
                            break;
                        case 4:
                            //烘干位
                            tvGroupState.setText("烘干中");
                            doingIndex = -1;
                            updateCircleLocation();
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            break;
                        case 5:
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            doingIndex = -1;
                            //清水清洗
                            tvGroupState.setText("清水清洗中");
                            updateCircleLocation();

                            //E1 是出错
                            if (225 == step) {
                                if (!errorDialogShow) {
                                    showErrorDialogOne("清水清洗错误,请检查供水");
                                }
                            }
                            break;
                        case 6:
                            ivPlayState.setBackgroundResource(R.mipmap.stop);
                            bleManageUtil.isPlaying = true;
                            LogUtil.d("研磨中 flow = 6  dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep());
                            //0x06工 作流程 正在研磨
                            doingIndex = dataDev;
                            updateCircleLocation();
                            if(name == 7)
                                updateCustomModeText(doingIndex);
                            else
                                updateModeText();
                            LogUtil.d("doingIndex = " + doingIndex + "  oldDoingIndex = " + oldDoingIndex);
//                            doingIndex
                            tvGroupState.setText("研磨中" + " 样品" + dataDev);
                            if (deviceStateFram.getStep() == 160) {
                                //stop();
                            }
                            if (step == 229) {
                                if (!errorDialogShow) {
                                    showErrorDialog("当前设备停止,确认后取下样品灌");
                                }
                                return;
                            }
                            if (step == 230) {
                                if (!errorDialogShow) {
                                    showErrorDialog("当前设备停止,确认后清理刀头残留物");
                                }
                                return;
                            }


                            break;

                        case 10:
                            LogUtil.d("研磨中 flow = 6  dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep());
                            //0x10工 作流程 停止
                            doingIndex = -1;
//                            updateCircleLocation();
                            LogUtil.d("doingIndex = " + doingIndex + "  oldDoingIndex = " + oldDoingIndex);
//                            doingIndex
                            if (deviceStateFram.getStep() == 160) {
                                cancle();
                                ivPlayState.setBackgroundResource(R.mipmap.play);
                                bleManageUtil.isPlaying = false;
                                tvGroupState.setText("停止工作");
                                updateCircleLocation();
                                timeStop();
                                soundPlayer.play(R.raw.didi, false);

                            }
                    }

                    if (deviceStateFram.getStep() == 160) {
                        if(isWhisKnife){
                            tv_wish_knife.setPressed(false);
                            tv_wish_knife.setEnabled(true);
                            isWhisKnife = !isWhisKnife;
                            BleManageUtil.getInstance().isPlaying = false;
                        }
                        if(isWhisPipe){
                            tv_wish_pipe.setPressed(false);
                            tv_wish_pipe.setEnabled(true);
                            isWhisPipe = !isWhisPipe;
                            BleManageUtil.getInstance().isPlaying = false;
                        }
                        if(isChangeKnife){
                            tv_changee_knife.setPressed(false);
                            tv_changee_knife.setEnabled(true);
                            isChangeKnife = !isChangeKnife;
                            BleManageUtil.getInstance().isPlaying = false;
                            showOffPowerDialog("操作刀头前请先关闭电源");
                        }

                        if(isLoop){
                            if(curLoopNum == loopNum){
                                stop();
                                return;
                            }
                            showConnectDialog("请更换样品");
                        }else{
                            stop();
                        }

                        cancle();
                        ivPlayState.setBackgroundResource(R.mipmap.play);
                        tvGroupState.setText("停止工作");
                        updateCircleLocation();
                        timeStop();
                        soundPlayer.play(R.raw.didi, false);
                        ToastUtils.showCenter("停止工作");

                    }
                }

                @Override
                public void onFail() {

                }
            };
        }

        BleManageUtil.getInstance().readDevicesState(myBleDeviceStateCallBack);
    }

    private void showConnectDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "停止", new String[]{"继续"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    curLoopNum++;
                    if(spManager.getCurModle() == 1)
                        start();
                    else
                        startCustom();
                } else if (position == -1) {
                    stop();
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showRunModleConnectDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"继续"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    if(spManager.getCurModle() == 1)
                        start();
                    else
                        startCustom();
                } else if (position == -1) {

                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }


    private BleDevice getLocationBlue() {
        aCache = ACache.get(this);
        byte[] bluetooth = aCache.getAsBinary("Bluetooth");
        Parcel unmarshall = ParcelableUtil.unmarshall(bluetooth);
        cacheBleDevice = null;
        cacheBleDevice = BleDevice.CREATOR.createFromParcel(unmarshall);
        return cacheBleDevice;
    }

    private void timeRestart() {
        chronometer.setBase(SystemClock.elapsedRealtime());
        //设置起始时间和时间格式，然后开始计时
        chronometer.setFormat("已用时间：%s");
        chronometer.start();
    }

    private void timeStop() {
        chronometer.stop();
    }


    private void updateModeText() {
        if (BleManageUtil.getInstance().isConnect) {
            int group = spManager.getGroup();

            String groupName = runTypelist.get(group).getName();

            BleManageUtil.getInstance().getConfigDataFrame(group, new MyBleGattCallback() {
                @Override
                public void onConfigSuccess(ConfigDataFram configDataFram) {
                    super.onConfigSuccess(configDataFram);
                    int time = configDataFram.getiTimeWork() / 10;
                    tvMode.setText("已选模式: " + groupName + "      转速 " + configDataFram.getiMotorSpeed() + "转/秒"
                            + "      研磨时间: " + time + "s");
                }
            });
        } else {
            tvMode.setText("当前蓝牙未连接");
            ToastUtils.showCenter("当前蓝牙未连接");
        }
    }
    private void updateCustomModeText(int doingIndex) {
        if (BleManageUtil.getInstance().isConnect) {

            int group;
            if(doingIndex > 0)
                group = demoLocationList.get(doingIndex-1).getGroup();
            else
                group = demoLocationList.get(doingIndex).getGroup();


            String groupName = runTypelist.get(group).getName();

            BleManageUtil.getInstance().getConfigDataFrame(doingIndex, new MyBleGattCallback() {
                @Override
                public void onConfigSuccess(ConfigDataFram configDataFram) {
                    super.onConfigSuccess(configDataFram);
                    int time = configDataFram.getiTimeWork() / 10;
                    tvMode.setText("已选模式: " + groupName + "      转速 " + configDataFram.getiMotorSpeed() + "转/秒"
                            + "      研磨时间: " + time + "s");
                }
            });
        } else {
            tvMode.setText("当前蓝牙未连接");
            ToastUtils.showCenter("当前蓝牙未连接");
        }
    }


    private void stop() {

        if(isLoop){
            curLoopNum = 1;
            isLoop = false;
        }
        //初始化研磨罐状态
        for (int i = 0; i < demoLocationList.size(); i++) {
            demoLocationList.get(i).setSelect(false);
        }
        spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
        runningDemoLocationList.clear();

        cancle();

        ivPlayState.setBackgroundResource(R.mipmap.play);
        tvGroupState.setText("停止工作");

        updateCircleLocation();
        timeStop();
        soundPlayer.play(R.raw.didi, false);

        BleManageUtil.getInstance().stopDevices();
    }

    private void start() {

        loopNum = spManager.getLoopNum();
        if(loopNum > 1){
            isLoop = true;
        }else{
            isLoop = false;
        }

        runningDemoLocationList.clear();
        for (NumberBean bean : demoLocationList) {
            runningDemoLocationList.add(bean);
        }

        //开启设备
        locationList = spManager.getLocationList();
        demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
        BleManageUtil.getInstance().beginDevices(1,spManager.getGroup(),demoLocationList);


        ivPlayState.setBackgroundResource(R.mipmap.stop);
        selectState();
    }

    private void startCustom() {

        loopNum = spManager.getLoopNum();
        if(loopNum > 1){
            isLoop = true;
        }else{
            isLoop = false;
        }

        runningDemoLocationList.clear();
        for (NumberBean bean : demoLocationList) {
            runningDemoLocationList.add(bean);
        }

        //开启设备
        locationList = spManager.getLocationList();
        demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
        BleManageUtil.getInstance().beginDevicesForCustom(1,demoLocationList);


        ivPlayState.setBackgroundResource(R.mipmap.stop);
        selectState();
    }
    private void startWhishknife() {

        BleManageUtil.getInstance().wishKnife();

        runWishTimer();
    }

    private void startWhishPipe() {

        BleManageUtil.getInstance().wishPipe();

        runWishTimer();
    }
    private void startChangeKnife() {

        BleManageUtil.getInstance().changeKnife();

        runWishTimer();
    }

    private void showWhisDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isWhisKnife = true;
                    BleManageUtil.getInstance().isPlaying = true;
                    tv_wish_knife.setPressed(true);
                    tv_wish_knife.setEnabled(false);
                    startWhishknife();
                } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showWhisPipeDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isWhisPipe = true;
                    BleManageUtil.getInstance().isPlaying = true;
                    tv_wish_pipe.setPressed(true);
                    tv_wish_pipe.setEnabled(false);
                    startWhishPipe();
                } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }
    private void showChangeKnifeDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isChangeKnife = true;
                    BleManageUtil.getInstance().isPlaying = true;
                    tv_changee_knife.setPressed(true);
                    tv_changee_knife.setEnabled(false);
                    startChangeKnife();
                } else if (position == -1) {
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }
    private void showOffPowerDialog(String msg) {
        AlertView mAlertView = new AlertView("", msg, "取消", new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {

                } else if (position == -1) {

                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void selectState() {
        runDymCodeTimer();
        timeRestart();
    }

    //这个方法可以在activity或者fragment销毁的时候调用，防止内存泄漏
    public void cancle() {
        if (timer != null) {
//            LogUtil.d("取消定时器");
            timer.cancel();
            timer = null;
        }
    }

    //这是定时器
    public void runDymCodeTimer() {
        LogUtil.d("runTimer启动定时器开始");
        if (timer != null) {
            LogUtil.i("onConnected","启动定时器 失败 timer != null");
            return;
        }
        LogUtil.i("onConnected","启动定时器 isConnect  " +BleManageUtil.getInstance().isConnect);
        if (bleManageUtil != null && BleManageUtil.getInstance().isConnect) {
            LogUtil.i("onConnected","启动定时器 isConnect  " +BleManageUtil.getInstance().isConnect);
            timer = new CountDownTimer(Long.MAX_VALUE, 2500) {
                @Override
                public void onFinish() {
                    cancel();
                }

                @Override
                public void onTick(long millisUntilFinished) {
                    if (bleManageUtil != null && BleManageUtil.getInstance().isConnect) {
                        getDeviceState();
                        //getDevicemodle();
                    }
                }
            }.start();
        }
    }

    //这是定时器
    public void runWishTimer() {
        LogUtil.d("runTimer启动定时器开始");
        if (timer != null) {
            LogUtil.d("启动定时器 失败 timer != null");
            return;
        }
        LogUtil.d("启动定时器 number = ");
        if (bleManageUtil != null && BleManageUtil.getInstance().isConnect) {
            LogUtil.d("启动定时器 number = ");
            timer = new CountDownTimer(Long.MAX_VALUE, 2000) {
                @Override
                public void onFinish() {
                    cancel();
                }

                @Override
                public void onTick(long millisUntilFinished) {
                    getDeviceState();
                }
            }.start();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            boolean isFinish = false;

            if (!isFinish) {
                if (secondTime - firstTime > 2000) {
                    Toast.makeText(MyApplication.application, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    return true;
                } else {
//                    AppManager.getAppManager().finishAllActivity();
                    return super.onKeyDown(keyCode, event);
                }
            } else {
                return false;
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    /**
     * 申请运行时权限，不授予会搜索不到设备
     */
    private void initPermissions() {
        if (ContextCompat.checkSelfPermission(this, "android.permission-group.LOCATION") != 0) {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{
                            "android.permission.ACCESS_FINE_LOCATION",
                            "android.permission.ACCESS_COARSE_LOCATION",
                            "android.permission.ACCESS_WIFI_STATE"},
                    1
            );
        }
    }


    @Override
    public Resources getResources() {
        //需要升级到 v1.1.2 及以上版本才能使用 AutoSizeCompat
        AutoSizeCompat.autoConvertDensityOfGlobal((super.getResources()));//如果没有自定义需求用这个方法
//        AutoSizeCompat.autoConvertDensity((super.getResources(),667, false);//如果有自定义需求就用这个方法
        return super.getResources();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ObserverManager.getInstance().deleteObserver(this);
    }

    @Override
    public void disConnected(BleDevice bleDevice) {
        //断开连接
        tvMode.setText("蓝牙已断开");
        ToastUtils.showCenter("是否重新连接");
        showConnectDialog("连接已断开,是否重新连接?", bleDevice);
    }

    @Override
    public void onConnected(BleDevice bleDevice) {
        tvMode.setText("蓝牙已连接");
        LogUtil.i("onConnected","连接成功");
        selectState();//连接成功后读取状态
        //getFirstDeviceModle();
        if(mHistoryAlertView != null){
            if(mHistoryAlertView.isShowing())
                mHistoryAlertView.dismiss();
        }
    }

    private void showCloseDialog() {
        AlertView mAlertView = new AlertView("", "是否停止运行", "取消", new String[]{"停止"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
//                    submit(0);
                    ToastUtils.showCenter("停止");
                    stop();
                } else if (position == -1) {
                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showErrorDialogOne(String message) {
        errorDialogShow = true;
        AlertView mAlertView = new AlertView("", message, null, new String[]{"确认"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    //确认是继续
                    BleManageUtil.getInstance().writeDeviceKeyFrame(1);
                    ToastUtils.showCenter("正在继续");
                } else if (position == -1) {
                    //取消是停止
//                    ToastUtils.showCenter("正在停止");
//                    BleManageUtil.getInstance().writeDeviceKeyFrame(0);
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
                errorDialogShow = false;
            }
        }).setCancelable(false);
        mAlertView.show();
    }

    private void showErrorDialog(String message) {
        errorDialogShow = true;
        AlertView mAlertView = new AlertView("", message, "停止", new String[]{"继续"},
                null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    //确认是继续
                    BleManageUtil.getInstance().writeDeviceKeyFrame(1);
                    ToastUtils.showCenter("正在继续");
                } else if (position == -1) {
                    //取消是停止
                    ToastUtils.showCenter("正在停止");
                    BleManageUtil.getInstance().writeDeviceKeyFrame(0);
//                    ToastUtils.showCenter("取消");
//                    submit(1);
                }
                errorDialogShow = false;
            }
        }).setCancelable(false);
        mAlertView.show();
    }

}